/**
 * 侧边栏菜单点击事件处理程序
 */
document.querySelectorAll('.sidebar .menu-item').forEach(function(item) {
    item.addEventListener("click", function() {
        chick_menu(this.getAttribute('data-target'));
    });
});

/**
 * 菜单点击事件处理程序
 * @param target
 */
// 首页切换书架
let click_count = 0;
let lastClickTime = 0;
let golb_flg = 1; // 1 正常  2 私密

// 目录页面添加私密书架
let private_click_count = 0;
let private_lastClickTime = 0;
let private_golb_flg = 1; // 1 正常  2 私密

function chick_menu(target) {
    document.querySelectorAll('.container > div').forEach(function(div) {
        div.classList.remove('active');
    });
    if (target) {
        document.getElementById(target).classList.add('active');
    }
    const now = new Date().getTime();
    // 点击3次触发事件
    if (target == 'home') {
        if (now - lastClickTime < 1500) {
            if (click_count === 2) {
                alert("触发特定标识1");
                click_count = 0;
                // 设置请求类型
                if(golb_flg == 1){
                    golb_flg = 2;
                }else{
                    golb_flg = 1;
                }
                get_books();
            }
            click_count++;
        } else {
            click_count = 1;
        }
        lastClickTime = now;
    }else if (target == 'chapters') {
        if (now - private_lastClickTime < 1500) {
            if (private_click_count === 2) {
                alert("触发特定标识2");
                private_click_count = 0;
                // 设置请求类型
                if(private_golb_flg == 1){
                    private_golb_flg = 2;
                }else{
                    private_golb_flg = 1;
                }
                update_private_book();
            }
            private_click_count++;
        } else {
            private_click_count = 1;
        }
        private_lastClickTime = now;
    }
}

// 字体大小设置
document.getElementById("font-size").addEventListener("change", function() {
    document.documentElement.style.fontSize = this.value;
});
// 背景颜色设置
document.getElementById("bg-color").addEventListener("change", function() {
    document.body.style.backgroundColor = this.value;
});
// 内容
document.getElementById("content_font-size").addEventListener("change", function() {
    document.getElementById("chapter-content").style.fontSize = this.value;
});
document.getElementById("content_bg-color").addEventListener("change", function() {
    document.getElementById("chapter-content").style.backgroundColor = this.value;
});

/**
 * 获取书籍列表
 */
function get_books()
{
    // 获取小说列表
    $.get("/novel/list?g="+golb_flg, function(response, _){
        let bookList = document.getElementById("bookshelf");
        bookList.innerHTML = "";
        // 将书籍列表添加到首页
        response.forEach(function(data) {
            addBookToShelf(data);
        });
    });
}

/**
 * 添加私密书籍
 * @returns 
 */
function update_private_book(){
    // 获取当前
    let book_id = document.getElementById("book_id").value;
    if(book_id == "" || parseInt(book_id) <= 0){
        alert("请选择书籍");
        return;
    }
    $.post({
        url: "/novel/update_private",
        data: JSON.stringify({"novel_id": book_id}),
        success: function(response, _){
            // alert(response.data);
            // console.log("更新书籍返回信息", response);
            get_books();
        }
    });
}

get_books();

/**
 * 获取章节列表
 * @param start_page   >2 底部  <1 顶部
 */
function get_menus(start_page=0)
{
    // 获取当前
    let book_id = document.getElementById("book_id").value;
    if (start_page > 1){
        start_page = parseInt(document.getElementById("end_page").value);
    }else if(start_page === 0){
        start_page = document.getElementById("chapter_id").value;
    }else {
        start_page = parseInt(document.getElementById("start_page").value) - 20;
    }
    if (start_page < 0){start_page = 0;}
    
    if (!start_page || parseInt(start_page) <= 0){
        start_page = 0;
    }
    let end_page = parseInt(start_page) + 20;

    // 将章节列表添加到页面
    var chapterList = document.getElementById("chapter-list");
    chapterList.innerHTML = "";
    $.get("/novel/menus?id=" + book_id + "&start="+ start_page +"&end=" + end_page,
        function(response, _){
            if (response.length === 0){
                alert("暂无数据");
                return;
            }
            document.getElementById("start_page").value = response[0]["order"];
            document.getElementById("end_page").value = response[response.length-1]["order"];
            response.forEach(function(chapter, index) {
                var listItem = document.createElement("li");
                listItem.textContent = chapter.name + "----" + chapter.order + "----" + chapter.drive_name;
                // 点击章节事件
                listItem.addEventListener("click", function() {
                    // 获取内容
                    show_contents(chapter.order);
                });
                chapterList.appendChild(listItem);
            });
        });
}

/**
 * 展示内容
 * @param chapter_id   章节id
 */
function show_contents(chapter_id=0)
{
    let book_id = document.getElementById("book_id").value;
    if (chapter_id === 0){
        chapter_id = parseInt(document.getElementById("chapter_id").value) + 1;
    }
    document.getElementById("chapter_id").value = chapter_id;
    $.post({
        url: "/novel/content",
        data: JSON.stringify({"novel_id": book_id, "chapter_id": chapter_id}),
        success: function(response, _){
            if (response.code !== 0){
                alert(response.data);
                return;
            }
            if (response.data.length === 0){
                alert("没有该章节信息");
                return;
            }
            // 添加内容
            let chapter_content = document.getElementById("chapter-content");
            chapter_content.innerHTML = "";

            // 创建章节名称
            var chapter_name = document.createElement("p");
            chapter_name.textContent = response.data.name + "   ---- "+ response.data.order +" ----   " + response.data.drive;
            chapter_name.classList.add("content-next-chapter_name");
            chapter_content.appendChild(chapter_name);

            // 创建内容
            var div = document.createElement("div");
            response.data.content.forEach(function (v, i) {
                // 创建自然段
                var p = document.createElement("p");
                p.textContent = v;

                // 点击此处开始播放
                p.addEventListener("click", function() {
                    // 获取内容
                    // read_and_scroll(i, null, book_id, chapter_id)
                });
                div.appendChild(p);
            });
            div.classList.add("chapter-content_div");
            chapter_content.appendChild(div);

            // 创建页脚数据
            var p = document.createElement("p");
            p.classList.add("content-next-page");
            // 上一页
            var pre_page = document.createElement("span");
            pre_page.textContent = "上一页";
            pre_page.addEventListener("click", function() {
                // 获取内容
                show_contents(parseInt(chapter_id) - 1);
            });
            p.appendChild(pre_page)
            // 下一页
            var next_page = document.createElement("span");
            next_page.textContent = "下一页";
            next_page.addEventListener("click", function() {
                // 获取内容
                show_contents(parseInt(chapter_id) + 1);
            });
            p.appendChild(next_page)
            // 切换源
            var source = document.createElement("span");
            source.textContent = "切换源";
            source.addEventListener("click", function() {
                switching_source(response.data.novel_id, response.data.order);
            });
            p.appendChild(source)

            // 自动滚动
            var scroll = document.createElement("span");
            scroll.textContent = "滚动"
            scroll.setAttribute("id", "scrollbutton");
            scroll.addEventListener("click", function() {
                auto_scroll();
            });
            p.appendChild(scroll)
            
            // 朗读
            var read = document.createElement("span");
            read.textContent = "朗读";
            read.setAttribute("id", "readbuttrn");
            read.addEventListener("click", function() {
                // switching_source(response.data.novel_id, response.data.order);
                read_noall(response.data.novel_id, response.data.order);
            });
            p.appendChild(read)

            chapter_content.appendChild(p);

            // 滑动到顶部
            chapter_content.scrollTop = 0;

            // 显示事件
            document.querySelectorAll('.container > div').forEach(function(div) {
                div.classList.remove('active');
            });
            document.querySelector('.chapter-content').classList.add('active');
        }
    });
}

/**
 * 更新书籍
 */
function get_new_chapter(flg)
{
    let novel_id = document.getElementById("book_id").value;
    if (novel_id === undefined || novel_id <= 0){
        alert("请选择书籍之后在更新");
        return;
    }
    $.post({
        url: "/novel/grabSaveNovels",
        data: JSON.stringify({"novel_id": novel_id, 'flg': flg}),
        success: function(response, _){
            // alert(response.data);
            console.log("更新书籍返回信息", response);
        }
    });
}

/**
 * 删除书架
 */
function delete_book_shelf()
{
    let novel_id = document.getElementById("book_id").value;
    if (novel_id === undefined || novel_id <= 0){
        alert("请选择书籍之后在更新");
        return;
    }
    $.post({
        url: "/novel/deleteBookShelf",
        data: JSON.stringify({"novel_id": novel_id}),
        success: function(response, _){
            alert(response.data);
            if (response.code === 0){
                // 刷新小说列表
                get_books();
            }
        }
    });
}

/**
 * 搜索书籍
 */
function search_books()
{
    // 书籍名称
    let name = $("#search_input").val();
    if (name === ""){
        alert("请输入书籍名称");
        return;
    }
    // 驱动名称
    let driver = $("input[name=driver]:checked").val();
    if (driver === ""){
        alert("请选择驱动");
        return;
    }
    let bookList = document.getElementById("book_search");
    // 清空内容
    bookList.innerHTML = "";

    // 搜索书籍
    $.get("/novel/searchBooks?name=" + name+"&driver="+driver, function(response, _){
        console.log("搜索获得内容", response);

        if (response.code === 0){
            let books = response.data;
            books.forEach(function (book, _){
                var bookItem = document.createElement("div");
                bookItem.classList.add("book-item");

                // 阅读
                var bookTitle = document.createElement("div");
                bookTitle.classList.add("book-title");
                bookTitle.textContent = book.name;
                bookItem.appendChild(bookTitle);

                var bookAuthor = document.createElement("div");
                bookAuthor.classList.add("book-author");
                bookAuthor.textContent = "作者：" + book.author;
                bookItem.appendChild(bookAuthor);

                var bookReadTime = document.createElement("div"); // 新增阅读时间元素
                bookReadTime.classList.add("book-read-time");
                bookReadTime.textContent = "最新章节：" + book.chapter;
                bookItem.appendChild(bookReadTime);

                // 添加点击时间，添加到书架的第一个位置，并移除当前书籍元素
                bookItem.addEventListener("click", function() {
                    // 添加书籍
                    add_books({"address": book.address, "name": book.name, "author": book.author});
                    // 切换页面
                    chick_menu("home");
                });

                bookList.appendChild(bookItem);
            });
        }else {
            alert(response.data);
        }
    });
}

/**
 *  添加书籍
 * @param data
 */
function add_books(data)
{
    $.post({
        url: "/novel/addBook",
        data: JSON.stringify(data),
        success: function (response, _){
            alert(response.data);
        }
    });
}

/**
 * 将书籍添加到书架
 * @param book      书籍对象
 */
function addBookToShelf(book)
{
    let bookList = document.getElementById("bookshelf");
    var bookItem= document.createElement("div");
    bookItem.classList.add("book-item");

    // 阅读
    var bookTitle = document.createElement("div");
    bookTitle.classList.add("book-title");
    bookTitle.textContent = book.name;
    bookItem.appendChild(bookTitle);

    var bookAuthor = document.createElement("div");
    bookAuthor.classList.add("book-author");
    bookAuthor.textContent = "作者：" + book.name + ", 更新:" + book.update;
    bookItem.appendChild(bookAuthor);

    var bookReadTime = document.createElement("div"); // 新增阅读时间元素
    bookReadTime.classList.add("book-read-time");
    bookReadTime.textContent = "阅读章节：" + book.chapter_name + "--" + book.chapter_order;
    bookItem.appendChild(bookReadTime);

    var lastReadChapter = document.createElement("div"); // 最新阅读章节
    lastReadChapter.classList.add("book-read-time");
    lastReadChapter.textContent = "最新章节：" + book.last_name + "--" + book.last_order;
    bookItem.appendChild(lastReadChapter);

    // 添加点击时间，添加到书架的第一个位置，并移除当前书籍元素
    bookItem.addEventListener("click", function() {
        // 移除当前书籍元素
        bookList.removeChild(bookItem);
        // 将当前书籍元素添加到书架的第一个位置
        bookList.insertBefore(bookItem, bookList.firstChild);
        // 设置当前书籍id
        document.getElementById("book_id").value = book.id;
        // 设置当前书籍阅读章节
        document.getElementById("chapter_id").value = book.chapter_order;
        // 设置章节数据
        get_menus();
        // 跳转到阅读页面
        chick_menu("chapters");
    });

    bookList.appendChild(bookItem);
}

/**
 * 切换书源
 * @param book_id           书籍id
 * @param chapter_order     章节
 */
function switching_source(book_id, chapter_order)
{
    layer.open({
        type: 2,
        area: ['90%', '60%'],
        content: "/novel/source_info?book_id="+book_id+"&chapter_order="+chapter_order,
        fixed: false, // 不固定
        maxmin: true,
        shadeClose: true,
        btnAlign: 'c',
      });
}

// 自动滚动项目
let now_p = 0;  // 当前章节
function auto_scroll()
{
    contentScrollUtils.all_start_fun($("#chapter-content"), $("#chapter-content>div>p"));
}

// 朗读且滚动
function read_and_scroll(i, data, book_id, chapter_order)
{
    let div = $("#chapter-content");
    let p_list = $("#chapter-content>div>p");
    // 拼接地址
    if(!data){
        data = book_id + "/" + chapter_order + "/{}.mp3";
    }
    var mp3 = window.location.protocol + '//' + window.location.host + "/static/voices/novels/" + data;
    // 结束上面的播放任务
    myAudio.stop_function();
    // 当前内容结束
    console.log("----------", i , p_list.length)
    if(i >= p_list.length){
        myAudio.audio = null;
        // 自动请求下一页
        show_contents(parseInt(chapter_order) + 1);

        // 自动朗读下一页
        setTimeout(function(){
            read_noall(book_id, parseInt(chapter_order) + 1);
        }, 2000);

        return;
    }
    // 查询文件大小
    fetch(mp3.replace(/\{\}/, i), { method: 'HEAD' }).then(response => {
        if (response.ok) {
            const contentLength = response.headers.get('Content-Length');
            // 空文件
            if(contentLength == 46){
                let p = $("#chapter-content>div>p").eq(i);
                p.css("color", "red");
                i = parseInt(i) + 1;
                console.log("空文件，下一节序号", i, p_list.length);
                read_and_scroll(i, data, book_id, chapter_order);
            }else{
                // 开始播放
                myAudio.set_url(mp3.replace(/\{\}/, i));
                
                // 设置监听函数
                set_function = function(){
                    // 开始函数触发
                    myAudio.start_function(function(){
                        $("#readbuttrn").text("正在播放");
                        // 开始滚动
                        let p = $("#chapter-content>div>p").eq(i);
                        // 总时长
                        let time = myAudio.get_duration();
                        contentScrollUtils.sign_start_fun(div, p, time);
                    });
                    // 暂停函数触发
                    myAudio.pause_function(function(){
                        $("#readbuttrn").text("继续播放");
                    });
                    // 结束触发
                    myAudio.ended_function(function(){
                        // 播放完毕
                        i = parseInt(i) + 1;
                        console.log("播放完毕,下一节序号", i, p_list.length);
                        // 开始下一轮的播放
                        read_and_scroll(i, data, book_id, chapter_order);
                    });
                    // 数据加载完成，开始播放
                    myAudio.start_play(function(){
                        myAudio.audio.play();
                    });
                }
                set_function();
            }
        } else {
            alert("无法获取文件大小，HTTP"+response.status);
        }
    })
    .catch(error => {
        alert('检查音频文件大小时发生错误:'+error);
    });
}

/**
 * 朗读
 * @param {*} book_id 
 * @param {*} chapter_order 
 */
function read_noall(book_id, chapter_order)
{
    let status = myAudio.update_status();
    if(!status){
        $.post({
            url: "/novel/read_noall",
            data: JSON.stringify({"novel_id": book_id, "chapter_id": chapter_order}),
            success: function (response, _){
                if(response.code == 0){
                    // 开始朗读
                    read_and_scroll(0, response.data, book_id, chapter_order);
                }else {
                    alert(response.data);
                }
            }
        });
    }
}